<template>
  <div>
    <t-dialog
      width="1166px"
      :visible.sync="visible"
      :closeBtn="false"
      placement="center"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="flex align-center justify-between" style="width: 100%;">
          <div class="drawer-head" @click="close">
            <p class="chevron-left">
              <icon-font name="chevron-left" size="18px"/>
            </p>
            <h3>出库</h3>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="footer-btn">
          <t-space size="22px">
            <div class="head-hint">
              <p>数量：</p>
              <p>{{ total }}</p>
            </div>
            <div class="head-hint">
              <p>金额：</p>
              <p>¥{{ totalPrice }}</p>
            </div>
          </t-space>
          <div>
            <t-button :theme="confirmBtn.theme" :loading="confirmBtn.loading" class="" @click="handleConfirm">
              <!--<icon-font name="check" size="22px" class="mr12" />-->
              {{ confirmBtn.content }}
            </t-button>
            <t-button theme="default" class="" @click="close">取消</t-button>
          </div>
        </div>
      </template>
      <div class="content mt16">
        <t-form :data="formData" :rules="rules" ref="form" label-align="top" layout="inline" @submit="onSubmit">
          <t-form-item name="ck_warehouse_id" style="width: 190px;">
            <template #label>
              <p class="form-label">出库仓库</p>
            </template>
            <t-select v-model="formData.ck_warehouse_id" disabled :options="warehouseOptions" filterable clearable
                      style="width: 100%;" placeholder="请选择仓库">
              <!-- 自定义底部内容 -->
              <div slot="panelBottomContent" class="select-panel-footer">
                <add-store @refresh="getStoreList"></add-store>
              </div>
            </t-select>
          </t-form-item>
          <t-form-item name="rk_warehouse_id" style="width: 190px;">
            <template #label>
              <p class="form-label">入库仓库</p>
            </template>
            <t-select v-model="formData.rk_warehouse_id" :options="warehouseOptions" filterable clearable
                      style="width: 100%;" placeholder="请选择仓库">
              <!-- 自定义底部内容 -->
              <div slot="panelBottomContent" class="select-panel-footer">
                <add-store @refresh="getStoreList"></add-store>
              </div>
            </t-select>
          </t-form-item>
          <t-form-item name="batch_no" style="width: 190px;">
            <template #label>
              <p class="form-label">批次编号</p>
            </template>
            <t-input v-model="formData.batch_no" style="width: 100%;" placeholder="请输入批次编号"></t-input>
          </t-form-item>
          <t-form-item name="product_data" style="width: 100%">
            <template #label>
              <p class="form-label">产品清单</p>
            </template>
            <t-table
              rowKey="id"
              :data="lists"
              :columns="columns"
              :stripe="stripe"
              :bordered="bordered"
              :hover="hover"
              :size="size"
              :max-height="maxHeight"
              :table-layout="tableLayout ? 'auto' : 'fixed'"
              :showHeader="showHeader"
              cellEmptyContent="-"
              resizable
              :loading="loading"
            >
              <template #title-slot-unit_price>
                <!--<p>进货价</p>-->
                <p>出库价</p>
                <!--<p>调拨价</p>-->
              </template>
              <template #title-slot-option></template>
              <template #unit_price="{row}">
                <p>￥{{ row.unit_price ? row.unit_price : '0.00' }}</p>
              </template>
              <template #option="{row}">
                <t-space size="12px">
                  <t-link theme="primary" class="edit-btn-color" hover="color" @click="handleEdit(row)">编辑</t-link>
                  <t-popconfirm theme="danger" confirm-btn="删除" @confirm="handleDelete(row)">
                    <template #content>
                      <div>
                        <h3 class="popconfirm-title">确认删除？</h3>
                        <p>删除后数据将不可以恢复！是否确认删除？</p>
                      </div>
                    </template>
                    <t-link theme="danger" class="opt-btn" variant="outline">删除</t-link>
                  </t-popconfirm>
                </t-space>
              </template>
            </t-table>
          </t-form-item>
        </t-form>

        <div class="add-btn-wrap">
          <t-button theme="default" variant="outline" @click="handleAdd">
            <p class="flex align-center">
              <icon-font name="add-circle" class="mr8"/>新增一条</p>
          </t-button>
        </div>
      </div>
    </t-dialog>


    <!-- 选择产品 -->
    <product-list ref="list" :storeId="storeId" @confirm="confirmProduct"></product-list>
    <!-- 编辑产品配置 -->
    <product-edit ref="edit" @change="changeProduct"></product-edit>
  </div>
</template>

<script>
import {IconFont, BrowseIcon} from "tdesign-icons-vue";
import {warehouseListApi} from "@/api/warehouse";
import AddStore from "@/pages/inventory/components/product-outbound/add-shtore.vue";
import ProductList from "@/pages/inventory/components/product-outbound/product-list.vue";
import ProductEdit from "@/pages/inventory/components/product-outbound/product-edit.vue";
import {outboundRecordCreateApi, warehousingRecordCreateApi} from "@/api/inventory";

export default {
  name: 'ProductOutbound',
  props: {
    storeId: [Number, String]
  },
  components: {
    ProductEdit,
    ProductList,
    AddStore,
    IconFont,
    BrowseIcon
  },
  data() {
    return {
      visible: false,
      confirmBtn: {
        content: '确定出库',
        theme: 'primary',
        loading: false
      },
      formData: {
        ck_warehouse_id: '', // 出库ID 必需
        rk_warehouse_id: '', // 入库ID 必需
        batch_no: '', // 批次编号 可选
        product_data: '', // [
                            //{
                            //  title: '', // 产品标题
                            //  product_id: '', // 产品ID
                            //  quantity: '', // 数量
                            //  is_sn: 1, // 开启SN序列号（0关闭；1开启）
                            //  sn: '', // SN数据
                            //  unit_price: '', // 含税单价（进货价）
                            //  remark: '', // 备注（50个字内）
                            //}
                          //] 可选产品清单(JSON数据）
      },
      rules: {
        ck_warehouse_id: [{required: true, message: '请选择调入仓库', trigger: 'change'}],
        product_data: [{required: true, message: '请选择出库产品', trigger: 'change'}]
      },

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        //{colKey: 'id', title: 'ID', align: 'center', width: 60,},
        //{colKey: 'thumb', title: '图片', align: 'center', width: 60,},
        {colKey: 'title', title: '产品名称', width: 200, ellipsis: true},
        {colKey: 'sn', title: 'SN', width: 240},
        {colKey: 'quantity', title: '数量', align: 'center', width: 140},
        {colKey: 'unit_price', title: '出库价', width: 140},
        //{colKey: 'unit_title', title: '单位', align: 'center', width: 80},
        {colKey: 'remark', title: '备注', width: 180},
        {colKey: 'option', title: 'title-slot-option', fixed: 'right', width: 140},
      ],
      maxHeight: 360,
      loading: false,

      warehouseOptions: [], // 仓库列表
      totalPrice: '0.00', // 总金额
      total: 0,
    }
  },
  mounted() {
    // 获取仓库列表
    //this.getStoreList()
    //this.$refs.list.open();
  },
  methods: {
    // 确定选择产品
    confirmProduct(list) {
      this.lists.push(...list)
      this.totalPrice = this.lists.reduce((total, item) => total + item.unit_price * item.quantity, 0).toFixed(2)
      let quantity = 0
      for (let i = 0; i < this.lists.length; i++) {
        quantity = quantity + this.lists[i].quantity
      }
      this.total = quantity
    },
    // 编辑产品配置
    changeProduct(data) {
      const index = this.lists.findIndex(item=> item.cId === data.cId)
      this.lists.splice(index, 1, data)
      this.totalPrice = this.lists.reduce((total, item) => total + item.unit_price * item.quantity, 0).toFixed(2)
      let quantity = 0
      for (let i = 0; i < this.lists.length; i++) {
        quantity = quantity + this.lists[i].quantity
      }
      this.total = quantity
    },
    // 添加产品
    handleAdd() {
      this.$refs.list.open();
    },
    // 编辑产品
    handleEdit(row) {
      this.$refs.edit.open(row);
    },
    // 删除产品
    handleDelete(row) {
      this.lists = this.lists.filter(item => item.product_id !== row.product_id)
      this.totalPrice = this.lists.reduce((total, item) => total + item.unit_price * item.quantity, 0).toFixed(2)
      let quantity = 0
      for (let i = 0; i < this.lists.length; i++) {
        quantity = quantity + this.lists[i].quantity
      }
      this.total = quantity
    },
    // 获取仓库列表
    getStoreList() {
      const params = {page: 1, limit: 9999}
      warehouseListApi(params).then(res => {
        // 分组 w_type: 0平台库 w_type：1 代理商库
        const platform = res.data.filter(item => item.w_type === 0)
        const agent = res.data.filter(item => item.w_type === 1)
        this.warehouseOptions = [
          {
            group: '平台库',
            value: 'platform',
            children: platform.map(item => ({label: item.name, value: item.id}))
          },
          {
            group: '代理商库',
            value: 'agent',
            children: agent.map(item => ({label: item.name, value: item.id}))
          }
        ]
      })
    },
    // 确定出库
    handleConfirm() {
      this.formData.product_data = this.lists.length ? JSON.stringify(this.lists) : ''
      this.$refs.form.submit()
    },
    onSubmit({validateResult, firstError}) {
      if (validateResult === true) {
        this.handleSubmit()
      } else {
        this.$message.error(firstError);
      }
    },
    handleSubmit() {
      outboundRecordCreateApi(this.formData).then(res=> {
        this.$message.success('出库成功')
        this.close()
        this.$emit('refresh')
      }).catch(err=> {
        console.log('err', err)
      })
    },
    open() {
      this.visible = true
      this.lists = [];
      this.formData.ck_warehouse_id = Number(this.storeId)
      this.formData = {
        ck_warehouse_id: Number(this.storeId), // 出库ID 必需
        rk_warehouse_id: '', // 入库ID 必需
        batch_no: '', // 批次编号 可选
        product_data: '',
      }
      this.$refs.form.reset()
      // 获取仓库列表
      this.getStoreList()
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

.head-hint {
  display: flex;
  align-items: center;

  font-size: 20px;
  font-weight: 400;
  line-height: 19.6px;
  text-align: left;

  p:first-child {
    color: var(--td-font-gray-2);
  }
}

.add-btn-wrap {
  padding-top: 24px;
  border-top: 1px solid #E1E1E1;
}

.footer-btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  width: 100%;
  background-color: #F9F9F9;
  border-bottom: 1px solid #F9F9F9;
  border-radius: 0 0 var(--td-radius-medium) var(--td-radius-medium);
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xxl);

  display: flex;
  align-items: center;
  justify-content: space-between;
}

.confirm-btn {
  width: 190px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}

.cancel-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  background-color: #B8B8B8;
  border-radius: var(--td-radius-medium);
}

/deep/ .t-dialog__body {
  padding-top: 0;
  margin-top: var(--td-comp-paddingTB-l);
}

/deep/ .t-dialog__footer {
  height: 75px;
}

</style>
